package com.cms.common.exception;

import com.cms.common.model.vo.ResponseResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;


@RestControllerAdvice
public class ApiExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return ResponseResult.fail(objectError.getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        return ResponseResult.fail(e.getConstraintViolations().iterator().next().getMessage());
    }

    @ExceptionHandler(ApiException.class)
    public ResponseResult APIExceptionHandler(ApiException e) {
        return ResponseResult.fail(e.getMsg());
    }

}